package com.minis;

import com.minis.beans.BeanDefinition;
import com.minis.beans.BeanFactory;
import com.minis.beans.BeansException;
import com.minis.beans.SimpleBeanFactory;
import com.minis.beans.XmlBeanDefinitionReader;
import com.minis.core.ClassPathXmlResource;
import com.minis.core.Resource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClassPathXmlApplicationContext implements BeanFactory {
    SimpleBeanFactory simpleBeanFactory;

    public ClassPathXmlApplicationContext(String fileName) {
        Resource resource = new ClassPathXmlResource(fileName);
        this.simpleBeanFactory = new SimpleBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(simpleBeanFactory);
        reader.loadBeanDefinition(resource);
    }

//    /**
//     * 读取并解析XML，生成bean定义
//     * @param fileName
//     */
//    private void readXml(String fileName) {
//        SAXReader saxReader = new SAXReader();
//        try {
//            URL url = this.getClass().getClassLoader().getResource(fileName);
//            Document document = saxReader.read(url);
//            Element rootElement = document.getRootElement();
//            for (Element e : (List<Element>) rootElement.elements()) {
//                String id = e.attributeValue("id");
//                String className = e.attributeValue("class");
//                BeanDefinition beanDefinition = new BeanDefinition(id, className);
//                beanDefinitions.add(beanDefinition);
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }

//    /**
//     * 通过反射，将bean存储到singletons map中去
//     */
//    private void instanceBeans() {
//        for (BeanDefinition beanDefinition : beanDefinitions) {
//            try {
//                singletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getName()).newInstance());
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//        }
//    }

    public Object getBean(String beanName) throws BeansException{
        return this.simpleBeanFactory.getBean(beanName);
    }

    @Override
    public boolean containsBean(String beanName) {
        return simpleBeanFactory.containsBean(beanName);
    }

    @Override
    public void registerBean(String beanName, Object obj) {
        simpleBeanFactory.registerBean(beanName, obj);
    }

}
